using System;
using QAssetBundle;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace ProjectSurvivor
{
	public partial class Ball : ViewController
	{
		
		
		void Start()
		{
			// 初始速度
			SelfRigidbody2D.velocity = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f)) *
			                           Random.Range(Global.SimpleBallSpeed.Value - 2f,
				                           Global.SimpleBallSpeed.Value + 2f);
			
			// 触碰到敌人
			HitBox.OnTriggerEnter2DEvent(collider =>
			{
				var hurtBox = collider.gameObject.GetComponent<HitHurtBox>();
				if (hurtBox && hurtBox.Owner.CompareTag("Enemy"))
				{
					int damageTimes = Global.SuperSimpleBall.Value ? Random.Range(2, 4) : 1;
					var enemy = hurtBox.Owner.GetComponent<IEnemy>();
					DamageSystem.CalculateDamage(Global.SimpleBallDamage.Value * damageTimes, enemy);
					
					// 一定概率击退敌人
					if (Random.Range(0f, 1f) < 0.5f && collider && collider.attachedRigidbody && Player.Default)
					{
						collider.attachedRigidbody.velocity =
							collider.NormalizedDirection2DFrom(this) * 5 + 
							collider.NormalizedDirection2DFrom(Player.Default) * 10;
					}
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			
			// 超级篮球
			Global.SuperSimpleBall.RegisterWithInitValue(unlocked =>
			{
				if (unlocked)
				{
					this.LocalScale(3);
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

		private void OnCollisionEnter2D(Collision2D other)
		{
			AudioKit.PlaySound(Sfx.BALL);
			// 获取法线
			Vector2 normal = other.GetContact(0).normal;

			SelfRigidbody2D.velocity = normal * Random.Range(0.5f, 1.5f) * Random.Range(Global.SimpleBallSpeed.Value - 2f,
				Global.SimpleBallSpeed.Value + 2f);

			SelfRigidbody2D.angularVelocity = Random.Range(-360f, 360f);
		}
	}
}
